package com.lv.service.dialog

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Build
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.lv.common.dialog.HintDialog
import com.lv.common.imp.OnPositionMediaTMore
import com.lv.common.imp.OnPositionMore
import com.lv.common.imp.OnPositionTMore
import com.lv.common.ktx.LoadSrc
import com.lv.common.utils.AnimationUtils
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.TimeUtil
import com.lv.common.utils.picengine.CompressEngine
import com.lv.common.utils.picengine.GlideEngine
import com.lv.common.utils.showToast
import com.lv.service.R
import com.lv.service.room.address.AddressDbHelper
import com.lv.service.room.category.CategoryBean
import com.lv.service.utils.YgxToolsKt
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.enums.PopupPosition
import kotlinx.coroutines.launch

/**
 * 作者： ygx
 * 创建日期：2022/10/10 10:32 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 *
 *
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：底部 签单
 */
class SignTopHPopupView(
    private val mContext: Context,
    private val mTitle: String,
    private val topH: Int = 0,
    private val mLayout: Int = R.layout.sign_toph_popup,
    private val mPositionTListener: OnPositionMediaTMore<String>? = null
) :
    BottomPopupView(mContext), View.OnClickListener {
    private var tvTitle: TextView? = null
    private var viewTop: View? = null
    private var viewShadow: TextView? = null
    private var ivClose: ImageView? = null
    private var ivCamera: ImageView? = null
    private var ivMedia: ImageView? = null
    private var ivDelete: ImageView? = null
    private var mTvTime: TextView? = null
    private var mTvPeroid: TextView? = null
    private var mLlTime: LinearLayout? = null
    private var mLlBook: LinearLayout? = null
    private var mStartTime = ""//选中的开始时间 默认今天
    private var mEndTime = ""//选中的结束时间  默认三个月后的今天
    private var mStartData = ""//日历的开始时间 默认今天
    private var mEndData = ""//日历的结束时间 默认24个月后的今天

    //    private var mSelectedTime = ""
    private val mBeans = mutableListOf<LocalMedia?>()

    override fun getImplLayoutId(): Int {
        return mLayout
    }

    override fun onCreate() {
        super.onCreate()
        initView()
        initEvnet()
    }

    private fun initView() {
        tvTitle = findViewById<TextView>(R.id.tv_title)
        viewTop = findViewById<View>(R.id.view_top)
        viewShadow = findViewById<TextView>(R.id.tv_submit)
        ivClose = findViewById<ImageView>(R.id.iv_close)
        ivCamera = findViewById<ImageView>(R.id.iv_camera)
        ivMedia = findViewById<ImageView>(R.id.iv_media)
        ivDelete = findViewById<ImageView>(R.id.iv_delete)

        mLlTime = findViewById<LinearLayout>(R.id.ll_time)
        mLlBook = findViewById<LinearLayout>(R.id.ll_book)
        mTvTime = findViewById<TextView>(R.id.tv_time)
        mTvPeroid = findViewById<TextView>(R.id.tv_peroid)

        ivClose?.setOnClickListener(this)
        viewTop?.setOnClickListener(this)
        ivCamera?.setOnClickListener(this)
        ivDelete?.setOnClickListener(this)
        viewShadow?.setOnClickListener(this)
        mLlTime?.setOnClickListener(this)
        mLlBook?.setOnClickListener(this)
        val layoutParams = viewTop?.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.height = topH
        tvTitle?.text = mTitle
        mStartTime = TimeUtil.getToday("yyyy-MM-dd")
        mEndTime = TimeUtil.AddMonths(mStartTime, 6)//默认开始结束时间间隔6个月
        mStartData = mStartTime
        mEndData = TimeUtil.AddMonths(mStartTime, 24)
//        val year = TimeUtil.getYear() + 1
//        val month = TimeUtil.getMonth()
//        val monthString = String.format("%02d", month)
//        mEndTime = "$year-$monthString"
//        val days = TimeUtil.getDaysByDate(mEndTime)
//        mEndTime = "$year-$monthString-$days"
//        mSelectedTime = mStartTime
        mTvTime?.text = "${mStartTime}至$mEndTime"
    }


    private fun initEvnet() {
        lifecycleScope.launch {
            //发行
            val datas =
                AddressDbHelper.getFindAllAddressSuspend(mContext)
            datas?.let {
                val list = mutableListOf<String>()
                for (i in 0 until datas.size) {
                    val element = datas[i]
                    val name = element.name
                    list.add(name)
                }
                mProvinceBeans.clear()
                val provices = YgxToolsKt.initProvincePeroidsNotAll(list)
                provices.let {
                    mProvinceBeans.addAll(provices)
                }
            }
        }
    }

    private fun showTimePicker() {
        val popupView =
            TimeStartEndPopupView(
                mContext, "合同期限", mStartTime, mEndTime,
                com.lv.common.R.drawable.bg_theme_5, mStartData, mEndData,
                positionListener = object : OnPositionTMore<String> {
                    override fun onClick(position: Int, vararg data: String?) {
                        mStartTime = data[0] ?: ""
                        mEndTime = data[1] ?: ""
                        mTvTime?.text =
                            "${mStartTime}至${mEndTime}"
                    }
                })
        XPopup.Builder(mContext)
            .isViewMode(true)
            .popupPosition(PopupPosition.Bottom)
            .asCustom(popupView)
            .show()
    }

    private val mProvinceBeans = mutableListOf<CategoryBean>()//省份期数
    private var mWheelPosition1 = 0
    private var mWheelPosition2 = 0
    private var mPeriod: String = ""
    private var mProvince: String = ""
    private fun showPeroidProvinceBottomDialog() {
        if (mProvinceBeans.isEmpty()) {
            return showToast("数据加载中……")
        }
        val mPopupView =
            PeroidProvinceSelectedPopupView(
                mContext, mProvinceBeans, mWheelPosition1, mWheelPosition2,
                object : OnPositionMore<List<CategoryBean>> {
                    override fun onClick(vararg args: Int, data: List<CategoryBean>?) {
                        mWheelPosition1 = args[0]
                        mWheelPosition2 = args[1]
                        mProvince = mProvinceBeans[mWheelPosition1].name
                        mPeriod = YgxToolsKt.getPeriod(
                            mProvinceBeans[mWheelPosition1].telSecondCategories?.get(
                                mWheelPosition2
                            )?.name ?: ""
                        )
                        mTvPeroid?.text = "$mProvince$mPeriod"
                    }
                }
            )

        XPopup.Builder(mContext)
            .isViewMode(true)//对于只使用一次的弹窗，推荐设置这个true
            .popupPosition(PopupPosition.Bottom)
            .asCustom(mPopupView)
            .show()

    }

    private fun checkPermission() {
        val hasCamera =
            PermissionXUtils.hasPermission(mContext as Activity, Manifest.permission.CAMERA)
        val permissions = mutableListOf<String>()
        if (!hasCamera) {
            permissions.add(Manifest.permission.CAMERA)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            val hasRead =
                PermissionXUtils.hasPermission(
                    mContext, Manifest.permission.READ_MEDIA_IMAGES
                )
            if (!hasRead) {
                permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
            }
        } else {
            val hasRead =
                PermissionXUtils.hasPermission(
                    mContext, Manifest.permission.READ_EXTERNAL_STORAGE
                )
            if (!hasRead) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
            }
        }
        if (permissions.size == 0) {
            showPicSelector()
        } else {
            PermissionXUtils.checkPermissBefore(
                mContext as FragmentActivity,
                permissions,
                "请授予相机、存储权限，以便使用相机拍摄或在手机相册中选择图片",
                callback = object : PermissionXUtilsCallback {
                    override fun permissionCallback(
                        allGranted: Boolean,
                        grantedList: List<String?>,
                        deniedList: List<String?>
                    ) {
                        if (allGranted) {
                            showPicSelector()

                        }
                    }
                })
        }

    }

    private fun showPicSelector() {
        PictureSelector.create(mContext)
            .openGallery(SelectMimeType.ofImage())//图库显示的类型
            .setImageEngine(GlideEngine.createGlideEngine())
            .setCompressEngine(CompressEngine.createCompressEngine())
            .setMaxSelectNum(1)//最大图片数
            .setMaxVideoSelectNum(1)//最大视频数
            .setMinSelectNum(1)
            .setImageSpanCount(4)
            .isMaxSelectEnabledMask(true)//不可点击时，是否显示朦层
            .isPreviewImage(true) // 是否可预览图片
            .isDisplayCamera(true) // 是否显示拍照按钮
            .isOriginalSkipCompress(true) // 是否压缩
            .setSelectedData(mBeans)
            .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
            .isWithSelectVideoImage(false)//是否可以同时选择视频和图片
            .forResult(object : OnResultCallbackListener<LocalMedia?> {
                override fun onResult(result: ArrayList<LocalMedia?>?) {
                    if (!result.isNullOrEmpty()) {
                        mBeans.clear()
                        val localMedia = result[0]
                        mBeans.add(localMedia)
                        ivMedia?.LoadSrc(localMedia?.compressPath ?: localMedia?.realPath)
                        ivMedia?.visibility = View.VISIBLE
                        ivDelete?.visibility = View.VISIBLE
                        ivCamera?.visibility = View.GONE
                    }

                }

                override fun onCancel() {}
            })
    }

    private fun setDismissDialog() {
        dismiss()
    }


    override fun onDestroy() {
        super.onDestroy()
        if (mHintDialog?.isShowing == true) {
            mHintDialog?.dismiss()
        }
    }

    override fun beforeDismiss() {
        super.beforeDismiss()


    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_close, R.id.view_top -> dismiss()
            R.id.iv_camera -> {
                checkPermission()
            }

            R.id.iv_delete -> {
                ivMedia?.visibility = View.GONE
                ivDelete?.visibility = View.GONE
                ivCamera?.visibility = View.VISIBLE
                mBeans.clear()
            }


            R.id.ll_time -> {
                showTimePicker()
            }

            R.id.ll_book -> {
                showPeroidProvinceBottomDialog()
            }

            R.id.tv_submit -> {
                if (mStartTime.isEmpty() || mEndTime.isEmpty()) {
                    AnimationUtils.setHintAnimation(mTvTime)
                    return showToast("请选择合同开始时间")
                }
                if (mBeans.isEmpty()) {
                    AnimationUtils.setHintAnimation(ivCamera)
                    return showToast("请选择门头或其它信息")
                }
                showHintDialog()

            }

        }
    }

    private var mHintDialog: HintDialog? = null
    private fun showHintDialog() {
        mHintDialog = HintDialog(
            mContext,
            "提示", "确认提交该合同内容？确认后不能更改",
            true, true,
            onDialogSureListener = {
                mPositionTListener?.onClick(0, mBeans, mStartTime, mEndTime, mProvince, mPeriod)
                dismiss()
            })
        mHintDialog?.show()
    }


}